import fs from 'node:fs'
import { execSync } from 'child_process'


function generateVersionCode(versionName) {
    let perfixCode = "";
    let suffixCode = "900";
    if (versionName.includes("-") > 0) {
        const codes = versionName.split("-");
        perfixCode = codes[0].replaceAll('.', '');
        if (codes[1].includes("alpha")) {
            suffixCode = `0${codes[1].split('.')[1].padStart(2, '0')}`;
        } else if (codes[1].includes("beta")) {
            suffixCode = `1${codes[1].split('.')[1].padStart(2, '0')}`;
        }
    } else {
        perfixCode = packageData.version.replaceAll('.', '');
    }
    return `${parseInt(perfixCode)}${suffixCode}`;
}

// 读取最新的版本号
const packageData = JSON.parse(fs.readFileSync('./package.json', 'UTF-8'))
const versionName = packageData.version;
const versionCode = generateVersionCode(versionName)
// 更新App应用版本号
const manifestData = JSON.parse(fs.readFileSync('./src/manifest.json', 'UTF-8'))
manifestData.versionName = versionName;
manifestData.versionCode = versionCode;
fs.writeFileSync('./src/manifest.json', JSON.stringify(manifestData, null, 2))
execSync(`git add CHANGELOG.md package.json src/manifest.json`)
execSync(`git commit -m "chore(release): ${versionName}"`)
execSync(`git tag "v${versionName}"`)
